<template>
  <div class="watermark-editor">
    <h3>创建水印</h3>
    <div class="input-section">
      <div class="form-group">
        <label for="contentInput">文本内容：</label>
        <textarea 
          id="contentInput" 
          :value="textContent" 
          @input="$emit('update:text-content', $event.target.value)"
          class="text-input" 
          placeholder="输入要显示的文本内容" 
          rows="5"
        ></textarea>
      </div>

      <div class="form-group">
        <label for="cssInput">CSS 样式：</label>
        <textarea 
          id="cssInput" 
          :value="cssStyle" 
          @input="$emit('update:css-style', $event.target.value)"
          class="text-input" 
          placeholder="输入CSS样式，例如：font-size:24px; color: #333; font-family: Arial;"
          rows="5"
        ></textarea>
      </div>

      <el-button 
        type="primary" 
        @click="generateImage"
                class="generate-btn"
      >
      生成水印图片
      </el-button>
    </div>

    <div v-if="imgUrl" class="result">
      <h4>水印预览：</h4>
      <img :src="imgUrl" alt="生成的水印" class="preview-img" />
    </div>

    <div v-if="imgUrl" class="video-section">
      <h3>应用到视频</h3>
      <div class="form-group">
        <label for="folderInput">视频文件夹路径：</label>
        <input 
          id="folderInput"
          v-model="videoFolder" 
          type="text" 
          class="text-input" 
          placeholder="输入视频文件夹路径"
        />
      </div>
      

      <el-button type="primary"
      @click="processVideos" :loading="processing"
        :disabled="!videoFolder || processing">
        开始处理视频
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, ref } from 'vue';
import { renderTxt2ImgBitmap, ImgClip } from '@webav/av-cliper';
import watermarkService from '../services/watermarkService.js';
import { ElMessage } from 'element-plus';

const props = defineProps({
  textContent: String,
  cssStyle: String
});

const imgUrl = ref('');
const videoFolder = ref('');
const processing = ref(false);

const emit = defineEmits([
  'update:text-content',
  'update:css-style',
  'generate',
  'process-complete'
]);

async function generateImage() {
  try {
    if (!props.textContent) {
      ElMessage.error('请输入文本内容');
      return;
    }

    // 水印处理
    const imgClip = new ImgClip(
      await renderTxt2ImgBitmap(
        props.textContent,
        props.cssStyle,
      )
    );

    // 生成数据URL
    const img = await imgClip.tick().then((bitmap) => {
      const canvas = document.createElement('canvas');

      if (bitmap.video) {
        canvas.width = bitmap.video.width;
        canvas.height = bitmap.video.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(bitmap.video, 0, 0);
        return canvas.toDataURL('image/png');
      } else {
        console.error('Invalid bitmap structure:', bitmap);
        throw new Error('无效的图像数据');
      }
    });

    imgUrl.value = img;
    emit('generate', img);
  } catch (error) {
    console.error('Image generation error:', error);
    ElMessage.error('生成图片失败: ' + (error.message || '未知错误'));
  }
}

async function processVideos() {
  if (!imgUrl.value || !videoFolder.value) {
    ElMessage.error('请提供水印图片和视频文件夹路径');
    return;
  }
  
  try {
    processing.value = true;
    
    // 将base64图片转换为文件对象
    const imageFile = await dataURLtoFile(imgUrl.value, 'watermark.png');
    // 使用 watermarkService 处理视频
    const results = await watermarkService.processVideosWithWatermark(videoFolder.value, imageFile);

    // 通知父组件处理已完成
    emit('process-complete', results);
    processing.value = false;
  } catch (error) {
    const msg = error.response.data.message
    ElMessage.error('处理视频失败: ' + (msg || '未知错误'));
    processing.value = false;
  }
}

// 工具函数：将dataURL转换为File对象
async function dataURLtoFile(dataurl, filename) {
  const res = await fetch(dataurl);
  const blob = await res.blob();
  return new File([blob], filename, { type: 'image/png' });
}
</script>

<style scoped>
.input-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
}

label {
  font-weight: bold;
  color: #333;
}

.text-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: monospace;
  resize: vertical;
}

.generate-btn, .process-btn {
  align-self: flex-start;
}


.process-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.result {
  margin: 24px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #eee;
}

.result h4 {
  margin-top: 0;
  margin-bottom: 10px;
}

.preview-img {
  max-width: 100%;
  border: 1px solid #eee;
  border-radius: 4px;
}

.video-section {
  margin-top: 30px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}
</style>